package com.liveinstars.account.business.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.liveinstars.account.business.domain.bo.AuthUserRole;
import com.liveinstars.account.business.domain.bo.User;
import com.liveinstars.account.business.mapper.AuthUserMapper;
import com.liveinstars.account.business.mapper.AuthUserRoleMapper;
import com.liveinstars.account.business.service.UserService;
import com.liveinstars.api.dto.PhoneSmsRequest;
import com.liveinstars.api.dto.UnifyAppUpdateUserInfoReq;
import com.liveinstars.common.utils.JsonUtil;
import com.onepiece.cache.service.CacheService;
import com.onepiece.shipelves.common.Result;
import com.onepiece.shipelves.common.enums.SystemExceptionEnum;
import com.onepiece.shipelves.common.exception.QuHuiRuntimeException;
import com.onepiece.shipelves.common.utils.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author tomsun28
 * @date 21:15 2018/3/17
 */
@Service("UserService")
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private AuthUserMapper userMapper;

    @Autowired
    private AuthUserRoleMapper authUserRoleMapper;

    @Autowired
    CacheService cache;

    @Override
    public String loadAccountRole(String appId) throws DataAccessException {

        return userMapper.selectUserRoles(appId);
    }

    @Override
    public List<User> getUserList() throws DataAccessException {
        return userMapper.selectUserList();
    }

    @Override
    public List<User> getUserListByRoleId(Integer roleId) throws DataAccessException {
        return userMapper.selectUserListByRoleId(roleId);
    }

    @Override
    public boolean authorityUserRole(String uid, int roleId) throws DataAccessException {
        AuthUserRole authUserRole = new AuthUserRole();
        authUserRole.setRoleId(roleId);
        authUserRole.setUserId(uid);
        authUserRole.setCreateTime(new Date());
        authUserRole.setUpdateTime(new Date());
        return authUserRoleMapper.insert(authUserRole) == 1? Boolean.TRUE : Boolean.FALSE;
    }

    @Override
    public boolean deleteAuthorityUserRole(String uid, int roleId) throws DataAccessException {
        AuthUserRole authUserRole = new AuthUserRole();
        authUserRole.setUserId(uid);
        authUserRole.setRoleId(roleId);
        return authUserRoleMapper.deleteByUniqueKey(authUserRole) == 1? Boolean.TRUE : Boolean.FALSE;
    }

    @Override
    public User getUserByAppId(String appId) throws DataAccessException {

        return userMapper.selectByUniqueKey(appId);
    }

    @Override
    public List<User> getNotAuthorityUserListByRoleId(Integer roleId) throws DataAccessException {

        return userMapper.selectUserListExtendByRoleId(roleId);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> getUsersByIds(List<Integer> userids) {
        if(userids == null || userids.size() == 0){
            return new ArrayList<>();
        }
        return userMapper.selectUserListByIds(userids);
    }


    @Override
    public Result<Boolean> smsLogin(PhoneSmsRequest phoneSmsRequest) {

        if(phoneSmsRequest.getMobile() == null || !StringUtil.isMobileNumber(phoneSmsRequest.getMobile())){
            return SystemExceptionEnum.ILLEGAL_REQUEST_PARAM.createResult();
        }
        String key = String.format("sms_flag_%s", phoneSmsRequest.getMobile());
        if(cache.exists(key)){
            return SystemExceptionEnum.AUTH_PHONE_CODE_EXIST.createResult();
        }

        Random random = new Random();
        String code = random.nextInt(99999) + "";
        cache.set(key, code, 60);
        HashMap<String,Object> map = new HashMap<>();
        //key必须为code
        map.put("code",code);

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4G3WyDpdrkiPQf2yzrhr", "HIXZVlrRvluuSmg3PgpEYdrneGRyFY");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneSmsRequest.getMobile());
        request.putQueryParameter("SignName", "趣会");
        request.putQueryParameter("TemplateCode", "SMS_205826373");
        request.putQueryParameter("TemplateParam", JsonUtil.toJson(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject object = JSON.parseObject(response.getData());
            if(object != null && "OK".equals(object.getString("Code"))){
                String authKey = String.format("sms_login_%s", phoneSmsRequest.getMobile());
                //短信验证码有效期6分钟
                cache.set(authKey, code, 360);
            }else {
                System.out.println(response.getData());
                logger.info("sms send response {}", response.getData());
            }

        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        Result<Boolean> result = new Result<>();
        result.setData(true);

        return result;
    }

    @Override
    public boolean updateUserInfo(UnifyAppUpdateUserInfoReq request) {
        if(request.getUid() == null || request.getUid() == 0){
            throw new QuHuiRuntimeException(SystemExceptionEnum.ILLEGAL_REQUEST_PARAM);
        }

        User user = new User();
        if(!StringUtils.isEmpty(request.getLogo())){
            user.setAvatar(request.getLogo());
        }
        if(!StringUtils.isEmpty(request.getNickName())){
            user.setNickName(request.getNickName());
        }
        user.setId(request.getUid());

        int i = userMapper.updateByPrimaryKeySelective(user);

        return i > 0;
    }

    @Override
    public boolean updateLocation(String location, Integer userId) {

        if(!StringUtils.isEmpty(location) && location.contains(",")){
            String[] split = location.split(",");
            cache.geoAdd("user_loc", String.valueOf(userId), Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            return true;
        }
        return false;
    }
}
